package uploadQRcodeBusiness;

import com.aliyun.oss.Upload;

import java.io.*;
import java.security.MessageDigest;

/**
 * Created by yangxianming on 2020/2/4.
 * oss工具
 */
public class UploadOSS extends Thread {
    private String path;
    private String resultPath;
    private String fileName;
    public UploadOSS(String path, String resultPath){
        //path需要//结尾 否则无法和文件名组合
        this.path = path;
        this.resultPath = resultPath;
    }
    @Override
    public void run() {
        File files = new File(path);
        String result = "";
        if (files.isDirectory()){
            for (File file: files.listFiles()){
                if (file.getName().startsWith(".")){
                    //跳过 . 开头的隐藏文件
                    continue;
                }
                if (!file.isDirectory()){
                    String fn = file.getName();
                    String line = "";
                    String encodeFn = encrypt(fn);
                    String uploadResult = Upload.upload(encodeFn, path + fn);
                    line += fn + " " + "https://efuli.oss-cn-hangzhou.aliyuncs.com/pic/" + encodeFn +" " + uploadResult + "\n";
                    System.out.print(line);
                    result += line;
                }
            }
        }else {
            String fn = files.getName();
            String line = "";
            String encodeFn = encrypt(fn);
            String uploadResult = Upload.upload(encodeFn, path);
            line += fn + " " + "https://efuli.oss-cn-hangzhou.aliyuncs.com/pic/" + encodeFn +" " + uploadResult + "\n";
            System.out.print(line);
            result += line;
        }


        try {
            FileOutputStream fos = new FileOutputStream(resultPath + "result.txt", true);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
//            Writer writer = new FileWriter(new File(resultPath + "result.txt"));
            osw.write(result);
            osw.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private String encrypt(String dataStr) {
        String slat = "&%5123***&&%%$$#@";
        try {
            dataStr = dataStr + slat;
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(dataStr.getBytes("UTF8"));
            byte s[] = m.digest();
            String result = "";
            for (int i = 0; i < s.length; i++) {
                result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}
